//
//  PasswordViewController.m
//  Village
//
//  Created by longrise on 2017/9/8.
//  Copyright © 2017年 程虎. All rights reserved.
//

#import "PasswordViewController.h"
#import "PasswordTableViewCell.h"
#import "LoginRuleViewController.h"
@interface PasswordViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    NSInteger selectIndex;
}
@property (nonatomic , strong) UITableView *mytableview;
@property (nonatomic ,strong)PooCodeView *pooCodeView;
@property (nonatomic ,strong)UIImageView *Pimage;
@property (nonatomic ,strong) NSMutableArray *leftary;
@property (nonatomic ,strong) NSMutableArray *tishiary;
@property (nonatomic ,strong) UIButton *surebutton;
@property (nonatomic ,strong) NSString *stra;
@property (nonatomic ,strong) NSString *strb;
@property (nonatomic ,strong) NSString *strc;
@property (nonatomic ,strong) NSString *strd;
@property (nonatomic ,strong) NSString *strf;
@property (nonatomic ,strong) NSString *poochange;
@property (nonatomic ,strong) NSString *style;// 1 注册 2 忘记密码
@property (nonatomic, copy) LongriseRouterBlock routerBlock;
@end

@implementation PasswordViewController

- (void)setParams:(id)obj block:(LongriseRouterBlock)block
{
    self.style = (NSString *)obj;
    self.routerBlock = block;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidDisappear:(BOOL)animated{
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kBackgroundColor;
    
    if ([self.style isEqualToString:@"1"]){
        [self Buildtheforgetpage];
        self.title = @"忘记密码";
        _tishiary =[[NSMutableArray alloc] initWithObjects:@"请输入账号",@"请设置新密码,6~20位字符",@"请输入图片验证码",@"请输入手机号",@"请输入短信验证码" ,nil];

    }else{
        [self Buildthepage];
        self.title = @"账号注册";
        _tishiary =[[NSMutableArray alloc] initWithObjects:@"请输入账号",@"请设置密码,6~20位字符",@"请输入图片验证码",@"请输入手机号",@"请输入短信验证码" ,nil];

    }
    [self gaindata];
}

- (void)Buildtheforgetpage{
    _mytableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, KDeviceHeight) style:UITableViewStylePlain];
    _mytableview.delegate = self;
    _mytableview.dataSource = self;
     _mytableview.scrollEnabled =NO; //设置tableview 不能滚动
    [self.view addSubview:_mytableview];
    
//    _pooCodeView = [[PooCodeView alloc] initWithFrame:CGRectMake(267*kScreenScaleX, 107.5*kScreenScaleY, 96*kScreenScaleX, 35*kScreenScaleY) andChangeArray:nil];
//    //注意:文字高度不能大于poocodeview高度,否则crash
//    _pooCodeView.textSize = 25*kScreenScaleY;
//    _pooCodeView.backgroundColor = K_Yanzhengma;
//    [_mytableview addSubview:_pooCodeView];
    
    _Pimage = [[UIImageView alloc] initWithFrame:CGRectMake(267*kScreenScaleX, 107.5*kScreenScaleY, 96*kScreenScaleX, 35*kScreenScaleY)];
//    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
//    NSURL *url  = [[NSURL alloc] initWithString:IMGCodeURL];
//    [_Pimage sd_setImageWithURL:url];
    
      [self tapAvatarView];
    [_mytableview addSubview:_Pimage];
    
    _Pimage.userInteractionEnabled = YES;
    UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView)];
    PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
    PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
    _Pimage.contentMode = UIViewContentModeScaleToFill;
    [_Pimage addGestureRecognizer:PrivateLetterTap];
    

    
    UIView *footview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KDeviceHeight, 600)];
    footview.backgroundColor = kBackgroundColor;
    _mytableview.tableFooterView = footview;
    
    _surebutton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_surebutton setTitle:@"提交" forState:UIControlStateNormal];
    _surebutton.tintColor = [UIColor whiteColor];
    _surebutton.layer.cornerRadius = 5.0*kScreenScaleX;//2.0是圆角的弧度，根据需求自己更改
    _surebutton.titleLabel.font = [UIFont systemFontOfSize:18*kScreenScaleX];
    _surebutton.frame = CGRectMake(30*kScreenScaleX, 20*kScreenScaleY, 315*kScreenScaleX, 45*kScreenScaleY);
//    [_surebutton setBackgroundImage:[UIImage imageNamed:@"BG"]forState:UIControlStateNormal];
    _surebutton.backgroundColor = K_Anniuhong;
    [_surebutton addTarget:self action:@selector(sureaction) forControlEvents:UIControlEventTouchUpInside];
    [footview addSubview:_surebutton];
}

- (void)Buildthepage{
    _mytableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, KDeviceHeight) style:UITableViewStylePlain];
    _mytableview.delegate = self;
    _mytableview.dataSource = self;
    _mytableview.scrollEnabled =NO; //设置tableview 不能滚动
    [self.view addSubview:_mytableview];
    
//    _pooCodeView = [[PooCodeView alloc] initWithFrame:CGRectMake(267*kScreenScaleX, 107.5*kScreenScaleY, 96*kScreenScaleX, 35*kScreenScaleY) andChangeArray:nil];
//    //注意:文字高度不能大于poocodeview高度,否则crash
//    _pooCodeView.textSize = 25*kScreenScaleY;
//    _pooCodeView.backgroundColor = K_Yanzhengma;
//    [_mytableview addSubview:_pooCodeView];
    
    _Pimage = [[UIImageView alloc] initWithFrame:CGRectMake(267*kScreenScaleX, 107.5*kScreenScaleY, 96*kScreenScaleX, 35*kScreenScaleY)];
    //    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
//    NSURL *url  = [[NSURL alloc] initWithString:@"http://192.168.7.214:8071/APP/logic/va/123.jpg"];
//    [_Pimage sd_setImageWithURL:url];
    _Pimage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:IMGCodeURL]]];
    [_mytableview addSubview:_Pimage];
    
    _Pimage.userInteractionEnabled = YES;
    UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView)];
    PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
    PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
    _Pimage.contentMode = UIViewContentModeScaleToFill;
    [_Pimage addGestureRecognizer:PrivateLetterTap];

    
    UIView *footview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KDeviceHeight, 600)];
    footview.backgroundColor = kBackgroundColor;
    _mytableview.tableFooterView = footview;
    
    UILabel *zhucelable = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, kDeviceWidth, 14)];
    NSString *set = @"注册即同意《村居通许可协议》";
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:set];
    //设置：在0-3个单位长度内的内容显示成红色
    [str addAttribute:NSForegroundColorAttributeName value:K_Anniuhong range:NSMakeRange(5, 9)];
    zhucelable.attributedText = str;
    [zhucelable setTextAlignment : NSTextAlignmentCenter] ;
    zhucelable.font = [UIFont systemFontOfSize:14];
    [footview addSubview:zhucelable];
    
 
    
    

    
    _surebutton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_surebutton setTitle:@"注册" forState:UIControlStateNormal];
    _surebutton.tintColor = [UIColor whiteColor];
    _surebutton.layer.cornerRadius = 5.0*kScreenScaleX;//2.0是圆角的弧度，根据需求自己更改
    _surebutton.titleLabel.font = [UIFont systemFontOfSize:18*kScreenScaleX];
    _surebutton.frame = CGRectMake(30*kScreenScaleX, 58*kScreenScaleY, 315*kScreenScaleX, 45*kScreenScaleY);
    //    [_surebutton setBackgroundImage:[UIImage imageNamed:@"BG"]forState:UIControlStateNormal];
    _surebutton.backgroundColor = K_Anniuhong;
    [_surebutton addTarget:self action:@selector(sureaction) forControlEvents:UIControlEventTouchUpInside];
    [footview addSubview:_surebutton];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 25, kDeviceWidth, 14)];
    v.backgroundColor = [UIColor clearColor];
    [footview addSubview:v];
    
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    tap.numberOfTapsRequired =1;
    tap.numberOfTouchesRequired =1;
    [v addGestureRecognizer:tap];
}

#pragma mark - 数据源方法

- (void)gaindata{
     _stra = [[NSString alloc] init];
     _strb = [[NSString alloc] init];
     _leftary =[[NSMutableArray alloc] initWithObjects:@"账   号",@"密   码",@"验证码",@"手机号",@"短信验证码" ,nil];
    
     }
// 返回多少组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
// 返回行数
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 5;
}
// 设置cell
- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    static NSString *cellID = @"id";
    PasswordTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil)
    {
        cell = [[PasswordTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.backgroundColor = [UIColor whiteColor];
    }
    if (indexPath.row == 0 ){
         cell.gainbutton.hidden = YES;
         cell.seebutton.hidden = YES;
    }else  if (indexPath.row == 1 ){
         cell.gainbutton.hidden = YES;
         cell.textfield.secureTextEntry = YES;

    }else  if (indexPath.row == 2 ){
         cell.seebutton.hidden = YES;
         cell.gainbutton.hidden = YES;
      
    }else  if (indexPath.row == 3 ){
         cell.textfield.keyboardType = UIKeyboardTypeNumberPad;
         cell.gainbutton.hidden = YES;
         cell.seebutton.hidden = YES;
     
    }else{
         cell.textfield.keyboardType = UIKeyboardTypeNumberPad;
         cell.seebutton.hidden = YES;
         cell.gainClickBlock = ^{
            [self getMSGCode];
        };
    }
    cell.textfield.tag = indexPath.row;
    cell.textfield.delegate = self;
    [cell.textfield addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    cell.leftlable.text = _leftary[indexPath.row];
    cell.textfield.placeholder = _tishiary[indexPath.row];
     [cell setSelectionStyle:UITableViewCellSelectionStyleNone];//cell点击之后没有视觉效果
   
    return cell;
}

- (void)textFieldWithText:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
            self.stra = textField.text;
            break;
        case 1:
            self.strb = textField.text;
            break;
        case 2:
            self.strc = textField.text;
            break;
        case 3:
            self.strd = textField.text;
            break;
        case 4:
            self.strf = textField.text;
            break;

        default:
            break;
    }
}

- (void)tapAvatarView{
    
    _Pimage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:IMGCodeURL]]];
}

- (void)tapAction{
    LoginRuleViewController *rule = [[LoginRuleViewController alloc] init];
    [self.navigationController pushViewController:rule animated:YES];
}
#pragma mark - 代理方法
//设置行高
- (CGFloat)tableView:(nonnull UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    return 50*kScreenScaleY;
}

#pragma mark - 提交方法
- (void)sureaction{
    if (!self.stra.length) {
        [MBProgressHUD showError:@"请输入您的账号！" toView:self.navigationController.view];
    }
    else if (!self.strb.length) {
        [MBProgressHUD showError:@"请输入您的密码！" toView:self.navigationController.view];
    }else if (!self.strd.length) {
        [MBProgressHUD showError:@"请输入手机号！" toView:self.navigationController.view];
    }
    else if (!self.strf.length) {
        [MBProgressHUD showError:@"请输入短信验证码！" toView:self.navigationController.view];
    }
    else if (![Tools checkUserNameRationality:self.stra]) {
        [MBProgressHUD showError:@"请输入6~15的字母或字母和数字的用户名！" toView:self.navigationController.view];
    }
    else if (![Tools checkPassWordRationality:self.strb]) {
        [MBProgressHUD showError:@"请输入6~20的字母和数字组成的密码！" toView:self.navigationController.view];
    }
    else {
        NSMutableDictionary *bean = [NSMutableDictionary dictionary];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        if ([self.style isEqualToString:@"1"]){
            [dict setObject:self.strb forKey:@"newpassword"];

        }else{
            [dict setObject:self.strb forKey:@"passwordcode"];
            [dict setObject:[Globle getInstance].visitorQQID.length > 0 ? [Globle getInstance].visitorQQID : @"" forKey:@"qqopenid"];
            [dict setObject:[Globle getInstance].visitorWXID.length > 0 ? [Globle getInstance].visitorWXID : @"" forKey:@"wechatopenid"];

        }
        [dict setObject:self.stra forKey:@"account"];
        [dict setObject:self.strd forKey:@"phone"];
        [dict setObject:self.strf forKey:@"msgcode"];
   
        [bean setValue:dict forKey:@"entitybean"];
        
        WeakSelf(weakSelf);
        
              //忘记密码
          if ([self.style isEqualToString:@"1"]){
              [NetRequestClass Post:ForgotURL Parameters:bean success:^(id result) {
                  
                  [MBProgressHUD hideHUDForView:weakSelf.navigationController.view];
                  [MBProgressHUD showError:result[@"message"] toView:weakSelf.navigationController.view];
                  [weakSelf.navigationController popViewControllerAnimated:YES];
              } failure:^(id valueCode, id error) {
                  [MBProgressHUD hideHUDForView:weakSelf.navigationController.view];
                  [MBProgressHUD showError:error toView:weakSelf.navigationController.view];
              }];
          }else{
              [NetRequestClass Post:RegisterURL Parameters:bean success:^(id result) {
                  [MBProgressHUD showError:result[@"message"] toView:weakSelf.navigationController.view];
                  [[Globle getInstance] saveAccountInfo:result[@"data"]];
                  [MBProgressHUD hideHUDForView:weakSelf.navigationController.view];
                  [MBProgressHUD showSuccess:result[@"message"] toView:weakSelf.navigationController.view Completion:^{
                      if (weakSelf.routerBlock) {
                          weakSelf.routerBlock([Globle getInstance].account);
                          [weakSelf.navigationController popViewControllerAnimated:YES];
                      }
                  }];
              } failure:^(id valueCode, id error) {
                  [MBProgressHUD hideHUDForView:weakSelf.navigationController.view];
                  
                  if ([error isEqualToString:@"账号存在"]){
                       [MBProgressHUD showError:@"该手机号已被注册!" toView:weakSelf.navigationController.view];
                  }else{
                       [MBProgressHUD showError:error toView:weakSelf.navigationController.view];
                  }
              }];
          }
    }
}

#pragma mark - 获取短信验证码
- (void)getMSGCode
{
    if (!self.strc.length) {
        [MBProgressHUD showError:@"请输入图片验证码！" toView:self.navigationController.view];
    }
    else if (!self.strd.length) {
        [MBProgressHUD showError:@"请输入手机号！" toView:self.navigationController.view];
    }else if ([Tools valiMobile:self.strd] == NO){
        [MBProgressHUD showError:@"手机号格式不正确！" toView:self.navigationController.view];
    }else{
        NSMutableDictionary *bean = [NSMutableDictionary dictionary];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:self.strd forKey:@"phone"];
        [dict setObject:self.strc forKey:@"imagecode"];
        [bean setValue:dict forKey:@"entitybean"];
        
        [NetRequestClass Post:RegisterGetMSGCodeURL Parameters:bean success:^(id result) {
            [MBProgressHUD hideHUDForView:self.navigationController.view];
           
            [MBProgressHUD showSuccess:result[@"message"] toView:self.navigationController.view Completion:nil];
             [MBProgressHUD showError:result[@"data"] toView:self.navigationController.view];
            
            if ([result[@"message"] isEqualToString:@"成功"]){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"Second" object:self userInfo:nil];
            }
            LSLog(@"msg -----  %@",result);
//            [MBProgressHUD showError:result[@"data"] toView:self.navigationController.view Completion:nil];
        } failure:^(id valueCode, id error) {
            [MBProgressHUD hideHUDForView:self.navigationController.view];
            if ([error isEqualToString:@"图形验证码错误"]){
                [MBProgressHUD showError:@"图片验证码输入错误" toView:self.navigationController.view];
            }else{
                [MBProgressHUD showError:error toView:self.navigationController.view];
            }

            
        }];
    }
}
@end
